package org.example;

import org.example.impl.clientEventImpl;
import org.example.impl.clientListenerThread;
import org.example.impl.heartbeatDetectionImpl;
import org.example.tools.utilsTools;

import java.io.IOException;
import java.net.*;

/**
 * 服务器处理工具类
 */
public class serverDatTcp {

    public ServerSocket serverSocket = null;
    public static void openServer(Integer port){
        serverDatTcp s = new serverDatTcp();
        s.serverStartPort(port);
    }
    private void serverStartPort(Integer port){
        try {
            serverSocket = new ServerSocket(port);
            clientListenerThread listenerThread = new clientListenerThread();
            listenerThread.setServerSocket(serverSocket);
            utilsTools.threadPoolExecutor.submit(listenerThread);
            utilsTools.threadPoolExecutor.submit(new heartbeatDetectionImpl());
        }catch (Exception e){e.printStackTrace();}
    }
    public static Socket clientStartConnect(String address, Integer port, clientEvent clientEvent){
        synchronized (serverDatTcp.class){
            try {
                Socket socket = new Socket(address, port);
                utilsTools.threadPoolExecutor.submit(new clientEventImpl(socket,clientEvent));
                return socket;
            }catch (Exception e){e.printStackTrace();}
        }
        return null;
    }
    public static void ClientSendMessages(Socket socket,byte[] data){
        try {
            if(socket !=null){
                socket.getOutputStream().write(data);
            }
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
    }
}
